package com.ryl.yomall.model.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @Date 15:48
 * @Author ryl
 * 远程调用拦截器工具类
 */

public class FeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //1:当前请求对象头中用户ID 传递给 远程调用请求对象的头中
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes ( );
        if(requestAttributes !=null){
            //当前微服务的请求对象
            HttpServletRequest request = requestAttributes.getRequest ( );
            if(request != null){

                //网关传递过来的真实用户ID
                String userId = request.getHeader ( "userId" );
                if(!StringUtils.isEmpty ( userId )){
                    requestTemplate.header ( "userId",userId );
                }
                //网关传递过来的临时用户ID
                String userTempId = request.getHeader ( "userTempId" );
                if(!StringUtils.isEmpty ( userTempId )){
                    requestTemplate.header ( "userTempId",userTempId );
                }
            }
        }
    }
}
